package cn.yunyichina.provider.order.service;

import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.PayService;
import cn.yunyichina.provider.iface.entity.alipay.AlipayFacepayMedicalCardQueryRequest;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.base.OrgApp;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.order.facepay.FacepayRequestVO;
import cn.yunyichina.provider.iface.entity.order.facepay.FacepayResponseVO;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.order.constant.FacePayMode;
import cn.yunyichina.provider.order.constant.OrderConst;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lullaby on 2017/1/17.
 */
public class BaseFacepayService {

    protected FacepayResponseVO getFacepayResponseVO(String hisOrdNum, String psOrdNum, String agtOrdNum, String openid, String account) {
        FacepayResponseVO facepayResponseVO = new FacepayResponseVO();
        facepayResponseVO.setHisOrdNum(hisOrdNum);
        facepayResponseVO.setPsOrdNum(psOrdNum);
        facepayResponseVO.setAgtOrdNum(agtOrdNum);
        facepayResponseVO.setOpenid(openid);
        facepayResponseVO.setAccount(account);

        return facepayResponseVO;
    }

    protected OrderExtVo generateOrder(FacepayRequestVO request) {
        HashMap<String, String> params = new HashMap<>();

        int payMode = request.getPayMode();

        Org org = BaseService.getBaseClient().getOrgByCode(request.getHospitalCode());
        OrgApp orgApp = BaseService.getBaseClient().getOrgAppByAppCode(request.getAppCode());

        params.put("org_id", org.getId());
        params.put("org_name", org.getOrgName());
        params.put("org_code", org.getOrgCode());

        params.put("platform_id", orgApp.getOrgId());
        params.put("platform_name", orgApp.getOrgName());
        params.put("platform_code", orgApp.getOrgCode());
        params.put("platform_org_app_name", orgApp.getOrgAppName());
        params.put("platform_org_app_code", orgApp.getOrgAppCode());

        params.put("dept_code", request.getDeptCode());
        params.put("dept_name", request.getDeptName());

        params.put("order_status", "1");
        params.put("pay_status", "1");

        params.put("order_type", request.getOrderType());
        params.put("user_name", request.getPatientName());
        if (!StringUtils.isEmpty(request.getPatientMobile())) {
            params.put("user_mobile", request.getPatientMobile());
        }
        params.put("medical_card_type", request.getCardType());
        params.put("medical_card_no", request.getCardNo());

        params.put("doctor_code", request.getDoctorCode());
        params.put("doctor_name", request.getDoctorName());

        params.put("his_order_no", request.getHisOrdNum());

        params.put("barcode", request.getAuthCode());

        if (FacePayMode.ALIPAYBARPAY.getCode() == payMode) {
            if (OrderConst.INSURANCE_ORDER.equals(request.getCanUseInsurance())) {
                params.put("pay_mode", "28");
                params.put("insurance_mode", "1");
                params.put("pay_code", "ALIPAYMEDICAREBARPAY");
                params.put("is_insurance", "1");
            } else {
                params.put("pay_mode", "24");
                params.put("insurance_mode", "0");
                params.put("pay_code", "ALIPAYBARPAY");
                params.put("is_insurance", "0");
            }
        } else if (FacePayMode.WXMICROPAY.getCode() == payMode) {
            params.put("pay_mode", "14");
            params.put("insurance_mode", "0");
            params.put("pay_code", "WXMICROPAY");
            params.put("is_insurance", "0");
        }

        params.put("pay_amount", request.getPayAmount());
        params.put("account_amount", request.getAccountAmount());
        params.put("medicare_amount", request.getMedicareAmount());
        params.put("insurance_amount", request.getInsuranceAmount());
        params.put("total_amount", request.getTotalAmount());

        params.put("pay_app_id", request.getAppId());
        params.put("collectors", request.getCollectors());
        params.put("created_time", DateUtils.getDatetime());

        if (OrderConst.INSURANCE_ORDER.equals(request.getCanUseInsurance())) {
            params.put("extra_params", "{" +
                    "\"serial_no\":\"" + request.getSerialNo() + "\"," +
                    "\"bill_no\":\"" + request.getBillNo() + "\"," +
                    "\"cancel_serial_no\":\"" + request.getCancelSerialNo() + "\"," +
                    "\"cancel_bill_no\":\"" + request.getCancelBillNo() + "\"" +
                    "}");
        }

        return BaseService.getBaseClient().addOrder(JsonUtils.toJsonString(params));
    }

    protected void updateOrderBySuccess(String id, Map payResult, int payMode) {
        OrderExtVo orderExtVo = new OrderExtVo();
        orderExtVo.setId(id);
        orderExtVo.setOrderStatus((short) 3);
        orderExtVo.setPayStatus((short) 3);

        if (FacePayMode.ALIPAYBARPAY.getCode() == payMode) {
            orderExtVo.setPaymentDealId((String) payResult.get("trade_no"));
            orderExtVo.setOpenId((String) payResult.get("buyer_user_id"));
            orderExtVo.setPayTime(
                    payResult.get("gmt_payment") == null
                            ? payResult.get("send_pay_date") == null
                            ? DateUtils.getDateTimeStr()
                            : (String) payResult.get("send_pay_date")
                            : (String) payResult.get("gmt_payment"));
        } else if (FacePayMode.WXMICROPAY.getCode() == payMode) {
            orderExtVo.setPaymentDealId((String) payResult.get("transaction_id"));
            orderExtVo.setOpenId((String) payResult.get("openid"));
            orderExtVo.setPayTime(DateUtils.formatDate((String) payResult.get("time_end"), "yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss"));
        }

        BaseService.getBaseClient().updateOrder(JsonUtils.toJsonString(orderExtVo));
    }

    protected void updateOrderByStatus(String id, int orderStatus, int payStatus) {
        OrderExtVo orderExtVo = new OrderExtVo();
        orderExtVo.setId(id);
        orderExtVo.setOrderStatus((short) orderStatus);
        orderExtVo.setPayStatus((short) payStatus);

        BaseService.getBaseClient().updateOrder(JsonUtils.toJsonString(orderExtVo));
    }

    protected AlipayFacepayMedicalCardQueryRequest buildAlipayFacepayMedicalCardQueryParameters(FacepayRequestVO request) {
        ResCommon<PaymentSettingResponse> paymentSettingResponseResCommon = PayService.getPayClient().queryPaymentSettingByAppId(request.getAppId());
        PaymentSettingResponse paymentSettingResponse = paymentSettingResponseResCommon.getResult();

        AlipayFacepayMedicalCardQueryRequest queryRequest = new AlipayFacepayMedicalCardQueryRequest();
        queryRequest.setPayPublicKey(paymentSettingResponse.getPayPublicKey());
        queryRequest.setPublicKey(paymentSettingResponse.getPublicKey());
        queryRequest.setPrivateKey(paymentSettingResponse.getPrivateKey());

        queryRequest.setAppId(request.getAppId());
        queryRequest.setMethod("alipay.commerce.medical.card.query");
        queryRequest.setFormat("JSON");
        queryRequest.setCharset("utf-8");
        queryRequest.setSignType("RSA");
        queryRequest.setTimestamp(DateUtils.getDatetime());
        queryRequest.setVersion("1.0");

        AlipayFacepayMedicalCardQueryRequest.BizContent bizContent = new AlipayFacepayMedicalCardQueryRequest.BizContent();
        bizContent.setAuthCode(request.getAuthCode());
        bizContent.setScene("bar_code");
        bizContent.setCardOrgNo("SZHRSS");

        queryRequest.setBizContent(JsonUtils.toJsonString(bizContent));

        return queryRequest;
    }

    protected boolean checkInsuranceFacePayRegistrationParams(FacepayRequestVO request) {
        FacepayRequestVO.MedicalRequestContent medicalRequestContent = request.getMedicalRequestContent();
        FacepayRequestVO.MedicalRequestContent.MZGHDJ mzghdj = medicalRequestContent.getMzghdj();

        return !StringUtils.isEmpty(request.getHospitalCode()) &&
                !StringUtils.isEmpty(request.getAppCode()) &&
                !StringUtils.isEmpty(request.getAppId()) &&
                !StringUtils.isEmpty(request.getHisOrdNum()) &&
                !StringUtils.isEmpty(request.getAuthCode()) &&
                !StringUtils.isEmpty(request.getOrderType()) &&
                !StringUtils.isEmpty(request.getCanUseInsurance()) &&
                !StringUtils.isEmpty(request.getPayAmount()) &&
                !StringUtils.isEmpty(request.getAccountAmount()) &&
                !StringUtils.isEmpty(request.getMedicareAmount()) &&
                !StringUtils.isEmpty(request.getInsuranceAmount()) &&
                !StringUtils.isEmpty(request.getTotalAmount()) &&

                !StringUtils.isEmpty(request.getCardType()) &&
                !StringUtils.isEmpty(request.getCardNo()) &&
                !StringUtils.isEmpty(request.getPatientName()) &&
                !StringUtils.isEmpty(request.getPatientMobile()) &&

                !StringUtils.isEmpty(request.getSerialNo()) &&
                !StringUtils.isEmpty(request.getCancelSerialNo()) &&
                !StringUtils.isEmpty(request.getCancelBillNo()) &&

                !StringUtils.isEmpty(medicalRequestContent.getYljgbm()) &&
                !StringUtils.isEmpty(medicalRequestContent.getYlzh()) &&
                !StringUtils.isEmpty(medicalRequestContent.getCzybm()) &&
                !StringUtils.isEmpty(medicalRequestContent.getCzyxm()) &&
                !StringUtils.isEmpty(mzghdj.getMzlsh()) &&
                !StringUtils.isEmpty(mzghdj.getKsbm()) &&
                !StringUtils.isEmpty(mzghdj.getKsmc()) &&
                !StringUtils.isEmpty(mzghdj.getGhlb()) &&
                !StringUtils.isEmpty(mzghdj.getGhf()) &&
                !StringUtils.isEmpty(mzghdj.getZjzj()) &&
                !StringUtils.isEmpty(mzghdj.getGhhj()) &&
                !StringUtils.isEmpty(mzghdj.getSsj()) &&
                !StringUtils.isEmpty(mzghdj.getZsj());
    }

    protected String buildInsuranceFacePayRegistrationParams(FacepayRequestVO request, OrderExtVo orderExtVo) {
        HashMap<String, String> params = new HashMap<>();

        FacepayRequestVO.MedicalRequestContent medicalRequestContent = request.getMedicalRequestContent();
        FacepayRequestVO.MedicalRequestContent.MZGHDJ mzghdj = medicalRequestContent.getMzghdj();

        params.put("pay_code", "ALIPAYMEDICAREBARPAY");

        params.put("app_id", request.getAppId());
        params.put("order_no", orderExtVo.getOrderNo());
        params.put("desc", "当面付：医保挂号 - " + orderExtVo.getOrgName());
        params.put("pay_amount", request.getPayAmount());
        params.put("total_amount", request.getTotalAmount());
        params.put("auth_code", request.getAuthCode());
        params.put("treatment", "REGISTRATION");
        params.put("name", request.getPatientName());
        params.put("mobile", request.getPatientMobile());
        params.put("cert_type", request.getCardType());
        params.put("cert_id", request.getCardNo());

        params.put("yljgbm", medicalRequestContent.getYljgbm());
        params.put("ylzh", medicalRequestContent.getYlzh());
        params.put("czybm", medicalRequestContent.getCzybm());
        params.put("czyxm", medicalRequestContent.getCzyxm());

        params.put("brlx", mzghdj.getBrlx());
        params.put("mzlsh", mzghdj.getMzlsh());
        params.put("ksbm", mzghdj.getKsbm());
        params.put("ksmc", mzghdj.getKsmc());
        params.put("ghlb", mzghdj.getGhlb());
        params.put("ghf", mzghdj.getGhf());
        params.put("zjzj", mzghdj.getZjzj());
        params.put("ghhj", mzghdj.getGhhj());
        params.put("ssj", mzghdj.getSsj());
        params.put("zsj", mzghdj.getZsj());

        params.put("serial_no", request.getSerialNo());
        params.put("bill_no", request.getBillNo());
        params.put("org_no", medicalRequestContent.getYljgbm());
        params.put("out_trade_no", orderExtVo.getOrderNo());
        params.put("gmt_out_create", DateUtils.getDatetime());

        return JsonUtils.toJsonString(params);
    }

    protected boolean checkInsuranceFacePayParams(FacepayRequestVO request) {
        return !StringUtils.isEmpty(request.getHospitalCode()) &&
                !StringUtils.isEmpty(request.getAppCode()) &&
                !StringUtils.isEmpty(request.getAppId()) &&
                !StringUtils.isEmpty(request.getHisOrdNum()) &&
                !StringUtils.isEmpty(request.getAuthCode()) &&
                !StringUtils.isEmpty(request.getOrderType()) &&
                !StringUtils.isEmpty(request.getCanUseInsurance()) &&
                !StringUtils.isEmpty(request.getPayAmount()) &&
                !StringUtils.isEmpty(request.getAccountAmount()) &&
                !StringUtils.isEmpty(request.getMedicareAmount()) &&
                !StringUtils.isEmpty(request.getInsuranceAmount()) &&
                !StringUtils.isEmpty(request.getTotalAmount()) &&

                !StringUtils.isEmpty(request.getCardType()) &&
                !StringUtils.isEmpty(request.getCardNo()) &&
                !StringUtils.isEmpty(request.getPatientName()) &&
                !StringUtils.isEmpty(request.getPatientMobile()) &&

                !StringUtils.isEmpty(request.getSerialNo()) &&
                !StringUtils.isEmpty(request.getBillNo()) &&
                !StringUtils.isEmpty(request.getCancelSerialNo()) &&
                !StringUtils.isEmpty(request.getCancelBillNo());
    }

    protected String buildInsuranceFacePayParams(FacepayRequestVO request, OrderExtVo orderExtVo) {
        HashMap<String, String> params = new HashMap<>();

        params.put("pay_code", "ALIPAYMEDICAREBARPAY");

        params.put("app_id", request.getAppId());
        params.put("order_no", orderExtVo.getOrderNo());
        params.put("desc", "当面付：医保 - " + orderExtVo.getOrgName());
        params.put("pay_amount", request.getPayAmount());
        params.put("total_amount", request.getTotalAmount());
        params.put("auth_code", request.getAuthCode());
        params.put("treatment", "TREATMENT");
        params.put("name", request.getPatientName());
        params.put("mobile", request.getPatientMobile());
        params.put("cert_type", request.getCardType());
        params.put("cert_id", request.getCardNo());

        params.put("hospital_code", request.getHospitalCode());
        params.put("serial_no", request.getSerialNo());
        params.put("bill_no", request.getBillNo());

        return JsonUtils.toJsonString(params);
    }

    protected boolean checkSelfFacePayParams(FacepayRequestVO request) {
        return !StringUtils.isEmpty(request.getHospitalCode()) &&
                !StringUtils.isEmpty(request.getAppCode()) &&
                !StringUtils.isEmpty(request.getAppId()) &&
                !StringUtils.isEmpty(request.getHisOrdNum()) &&
                !StringUtils.isEmpty(request.getAuthCode()) &&
                !StringUtils.isEmpty(request.getOrderType()) &&
                !StringUtils.isEmpty(request.getCanUseInsurance()) &&
                !StringUtils.isEmpty(request.getPayAmount()) &&
                !StringUtils.isEmpty(request.getAccountAmount()) &&
                !StringUtils.isEmpty(request.getMedicareAmount()) &&
                !StringUtils.isEmpty(request.getInsuranceAmount()) &&
                !StringUtils.isEmpty(request.getTotalAmount()) &&

                !StringUtils.isEmpty(request.getCardType()) &&
                !StringUtils.isEmpty(request.getCardNo()) &&
                !StringUtils.isEmpty(request.getPatientName());
    }

    protected String buildSelfFacePayParams(FacepayRequestVO request, OrderExtVo orderExtVo) {
        HashMap<String, String> params = new HashMap<>();

        if (FacePayMode.ALIPAYBARPAY.getCode() == request.getPayMode()) {
            params.put("pay_code", FacePayMode.ALIPAYBARPAY.toString());
        } else if (FacePayMode.WXMICROPAY.getCode() == request.getPayMode()) {
            params.put("pay_code", FacePayMode.WXMICROPAY.toString());
        }

        params.put("app_id", request.getAppId());
        params.put("order_no", orderExtVo.getOrderNo());
        params.put("desc", "当面付：自费 - " + orderExtVo.getOrgName());
        params.put("pay_amount", request.getPayAmount());
        params.put("auth_code", request.getAuthCode());
        params.put("scene", "bar_code");

        return JsonUtils.toJsonString(params);
    }

}
